<?php

class myzhuaqu
{
    public $url;
    public $nr;
    public $cookie;

    function re($re)
    {
        $temp=$this->nr;
        if(preg_match("/&&&/",$re)){
            preg_match("/$re/Uisx", $temp, $nn);
            $temp=$nn[1];
        }
        preg_match_all("/$re/Uisx", $temp, $nn);
        return $this->clwz($nn[1][0]);
    }

    function retable($name)
    {
        preg_match_all("/<div\s+class=\"tableInfo\">\s*$name\s*<\/div>.*(<table[^<>]*>.*<\/table>)/Uisx", $this->nr, $nn);
        $nn[1][1] = preg_replace("/(width|align|style|border)=[^<>\s]*/isx", "", $nn[1][0]);
        $nn[1][1] = preg_replace("/<\!\-\-(.*)\-\->/Uisx", "", $nn[1][0]);
        preg_match_all("/<tr[^<>]*>(.*)<\/tr>/Uisx", $nn[1][1], $nntr);
        $return = array();
        $firstTr = array();
        for ($i = 0; $i < count($nntr[1]); $i++) {
            preg_match_all("/<t(?:d|h)\b[^<>]*>(.*)<\/t(?:d|h)>/Uisx", $nntr[0][$i], $nntd);
            if ($i == 0) {
                $firsttds = count($nntd[1]);
                $hascol = ($firsttds > 1) ? true : false;
                if ($hascol) {
                    $firstTr = $nntd[1];
                    continue;
                }
            }
            $tds = count($nntd[1]);
            if ($hascol) {
                if ($tds == $firsttds) {
                    for ($j = 0; $j < $tds; $j++) {
                        $return[$i][$firstTr[$j]] = $this->clwz($nntd[1][$j]);
                    }
                } else {
                    $bz = trim(strip_tags($nntr[1][$i], "<a>"));
                    if ($bz) $return[$i]['备注'] = $bz;
                }
            } else {
                $return[$i] = $this->clwz($nntd[1][0]);
            }
        }
        return $return;
    }

    function clwz($str)
    {
        $str = preg_replace("/\s+/", "", trim(strip_tags($str)));
        return $str;
    }


    function curl($url,$Querystring="",$cookie2="",$Referer="",$header=0,$proxy=""){
        static $cookie;
        $host=whost($url);
        $durl=$url;
        //$url=preg_replace("/XDEBUG_SESSION_START=[0-9]+\&?/","XDEBUG_SESSION_START=".$_REQUEST['XDEBUG_SESSION_START'],$url);
        $Referer=($Referer=="")?"http://{$host}/":$Referer;
        $timeout=5;
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");
        //curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //curl_setopt($ci, CURLOPT_PROXY, '192.168.1.130:8080');//自己设置的代理，
        //curl_setopt($ci, CURLOPT_PROXYUSERPWD, 'username:pwd');//公司上网的账号密码，
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        /*if(preg_match("/multipart/Uisx",$post)){
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
            curl_setopt( $ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data; boundary=$boundary"));
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }*/
        if($Referer!=""){
            curl_setopt($ch, CURLOPT_REFERER, $Referer);
        }
        if($cookie2!=""){
            curl_setopt($ch, CURLOPT_COOKIE, $cookie2);
        }
        if($Querystring!=""){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $Querystring);
        }
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLINFO_HEADER_OUT, $header);
        $r = curl_exec($ch);
        curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
        $GLOBALS['returncookie']=$cookie=getcookies($r,$cookie2);
        if (preg_match("/Location:\s*([^\r\n]+)/isx", $r, $nn)) {
            $GLOBALS['jumpurl']="";
            //$url=preg_replace("/XDEBUG_SESSION_START=[0-9]+\&?/","XDEBUG_SESSION_START=".$_REQUEST['XDEBUG_SESSION_START'],$url);
            if($url!=trim($nn[1])&&$oldurl!=$url) {
                $oldurl=$url;
                $durl = quanurl(trim($nn[1]),$oldurl);
                $GLOBALS['jumpurl']=$url;
                $r = $this->curl($durl,"", $cookie, $Referer,$header,$proxy);
            }
        }

        if (preg_match("/self\.location=[\"']([^<>\"\']*)[\"']/Uisx", $r, $nn)) {
            $GLOBALS['jumpurl']="";
            $nn[1]=quanurl($nn[1],$durl);
            if($durl!=trim($nn[1])||$oldurl!=$durl||$cookie!=$oldcookie) {
                $oldurl=$durl;
                $oldcookie=$cookie;
                $zz=parse_url($durl);
                $durl = quanurl(trim($nn[1]), "http://".$zz[host]."/");
                  $r = $this->curl($durl,"", $cookie, $Referer,1,$proxy);
                $GLOBALS['jumpurl']=$durl;
            }
        }
        if(preg_match("/^http\/(.*)(?:\r\n\r\n|\n\n)(.+?)$/Uis", $r, $nn)){
            $body = $nn[2];
            if (!preg_match("/html|img/Uisx",$r)&&@gzinflate(substr($body, 10))) {
                $body = gzinflate(substr($body, 10));
            }
        }else{
            $body=$r;
        }
        if($header){
            $result=$nn[1]."\r\n\r\n".$body;
        }else{
            $result=$body;
        }
        $result=bianma($result);
        return $result;
    }

	function fopenr($filepath){
		$fn=fopen($filepath,"r");
		$nr=fread($fn,filesize($filepath));
		fclose($fn); 
		return $nr;
	}

	function fopenw($filepath,$nr){
		$fn=fopen($filepath,"w");
		fwrite($fn,$nr);  
		fclose($fn);  
	}

    function urlsavebd($url,$referer=""){
        $q = new myzhuaqu();
        if(preg_match("/\.(jpg|jpeg|gif|png|bmp)$/Uisx",$url)){
            $nr=@file_get_contents($url);
        }else{
            $nr=$this->curl($url, "", $_REQUEST['cookie'], $referer);
            $nr = dquanurl($nr, $url);
            if(preg_match("/\.(php|do|jsp|asp|aspx|css|html|htm)$/Uisx",$url)){
                $nr=preg_replace("/([\"']?)(https?\:\/\/.*)(\/.*\.(jpg|jpeg|gif|png|js|css))\\1/Uisx","\\1/resource"."\\3\\1",$nr);
            }
        }
        if($nr=="") return "";
        $path=$this->urltobdpath($url);
        $this->fopenw($path,$nr);
        return $nr;
    }

    function urltobdpath($url){
        $path=preg_replace("/https?\:\/\/.*\//Uisx","",$url);
        $path=substr(__FILE__,0,-12)."resource/".preg_replace("/\?.*$/","",$path);
        createdir(dirname($path));
        return $path;
    }
}

function fopenr($filepath){
    $fn=fopen($filepath,"r");
    $nr=fread($fn,filesize($filepath));
    fclose($fn);
    return $nr;
}

function fopenw($filepath,$nr){
    $fn=fopen($filepath,"w");
    fwrite($fn,$nr);
    fclose($fn);
}

function bianma($pagehtml){
    if (preg_match("/<meta[^<>]+charset=(['\"]?)([a-zA-Z0-9\-]+?)\\1/Uisx", $pagehtml, $matches)) {
        $charset = str_replace("-", "", strtolower($matches[2]));
    }
    if ($charset != "utf8") {
        $charset = (!preg_match("/（，|。|？|；）/", $pagehtml)) ? $charset : "utf8";
    }

    $e = mb_detect_encoding($pagehtml, "UTF-8, ISO-8859-1, GBK");
    if ($charset != "utf8"&&$e != "UTF-8") {
        $pagehtml = @mb_convert_encoding($pagehtml, "utf-8", "GB2312, GBK,ISO-8859-1");
        $e = mb_detect_encoding($pagehtml, "UTF-8, ISO-8859-1, GBK");
        if($e=="ISO-8859-1"){
            $pagehtml=iconv("GB2312","UTF-8//IGNORE",$pagehtml);
        }
    }
    return $pagehtml;
}

function whost($str)
{
    preg_match_all("/http\:\/\/([^\/]+)/", $str, $nn);
    $whost = $nn[1][0];
    return $whost;
}

function host($str)
{
    $str=($str=="")?$this->url:$str;
    preg_match_all("/http\:\/\/(?:[^<>\.]+\.)??([^<>\/]+(?<!www)(\.(com|gov|edu|org)(?=\/|$|\.cn)|\.cn(?=\/|$|\:)|\.net|\.cc|\.tv|\.hk|\.tw)+?)/Uisx", $str, $nn);
    $host = $nn[1][0];
    $host = preg_replace("/^(?:[^<>]*\.)*([a-z0-9_]+\.(com|gov|edu|org|cn))/Uisx", "\\1", $host);
    if($str=="") $this->host=$host;
    return $host;
}


function getliebiao($url){
    $url="http://collect1.longsunhd.com/collect/index.php?gather_type=6&s_url=".urlencode($url)."&bug=0&api=1";//&bug=1:重新抓取参数
    $data=json_decode(curl($url),1);
    return $data;
}

function getnr($url){
    $url="http://collect1.longsunhd.com/collect/index.php?gather_type=1&s_url=".urlencode($url)."&bug=0&api=1";//&bug=1:重新抓取参数
    $data=json_decode(curl($url),1);
    return $data;
}

function quanurl($subUrl, $wurl, $baseurl = "")
{
    if(preg_match("/%/",$subUrl)) $subUrl=urldecode($subUrl);
    if (is_array($subUrl) || $subUrl == "") return "";
    preg_match("/(https?)\:\/\//Uisx",$wurl,$nn);
    $https=$nn[1];
    $baseurl = preg_replace("/(https?\:\/\/[^\/]+)$/Uisx", "\\1/", $baseurl);
    $subUrl = str_replace('\\', "/", trim($subUrl));
    $subUrl = str_replace('&amp;', "&", $subUrl);
    $subUrl = preg_replace("/^\.\?/", "?", $subUrl);
    $wurl = ($baseurl) ? $baseurl : $wurl;
    $wurl = preg_replace("/\?.*$/Uisx", "", $wurl);
    preg_match_all("/(https?\:\/\/([^\/]*?))(.*)$/Uimx", $wurl, $mm);
    $host = $mm[2][0];
    $subUrl=preg_replace("/^\/\//","http://",$subUrl);
    if (substr($subUrl, 0, 7) == "http://"||substr($subUrl, 0, 8) == "https://") {
        $newurl = $subUrl;
    } elseif (preg_match("/^\//", $subUrl)) {
        $newurl = "{$https}://" . $host . $subUrl;
    } elseif (preg_match("/^\.\.\//", $subUrl)) {
        $tmsuburl = $subUrl;
        $tempparentUrl = $wurl;
        preg_match_all("/(\.\.\/)/Uisx", $subUrl, $nn);
        for ($i = 0; $i < count($nn[1]); $i++) {
            $tmsuburl = preg_replace("/^\.\.\//", "", $tmsuburl);
            if(!preg_match("/http\:\/\/[^<>\/]+\/?$/Uisx",$tempparentUrl)) {
                $tempparentUrl = preg_replace("/(?!<\/)\/[^<>\/]*\/[^<>\/]*$/", "/", $tempparentUrl);
            }
        }
        $newurl = preg_replace("/\/$/", "", $tempparentUrl) . "/" . $tmsuburl;
    } elseif (preg_match("/^[^\.\/\?]/", $subUrl)) {
        preg_match("/^(.*)\//Uisx", $subUrl, $nna);
        preg_match("/http\:\/\/.*\/(.*)\//Uisx", $wurl, $nnb);
        if ($nnb[1] == $nna[1]) {
            $newurl = "http://" . $host . "/" . $subUrl;
        } else {
            $newurl = dirname2($wurl) . "/" . $subUrl;
        }
    } elseif (preg_match("/^\?/", $subUrl)) {
        $newurl = preg_replace("/\?.*$/U", "", $wurl) . $subUrl;
    } else {
        $newurl = preg_replace("/\/[^\/]*$/", "/", $wurl) . $subUrl;
    }
    $newurl = preg_replace("/\/\.\//", "/", $newurl);
    $newurl = preg_replace("/\/http\:\//", "/", $newurl);
    $newurl = preg_replace("/[\r\n]/", "", $newurl);
    return $newurl;
}

function dquanurl($nr, $wurl, $baseurl="")
{
    $nr = preg_replace_callback("/(src|location|<link[^>]*href|<EMBED[^>]*VALUE|action|background|imgurl|<PARAM\s+NAME\=movie\s+VALUE|href)\s*=\s*(\" | \')?([^\"\'\>\s]+)(\\2|(?=\>)|\s)/Uisx", function($em) use($wurl,$baseurl){
        return "{$em[1]}=\"".quanurl("{$em[3]}",$wurl,$baseurl)."\"";
    }, $nr);
    $nr = preg_replace_callback("/url\((\"|' |)?([^<>\s\"']+)\\1\)/Uisx", function($em) use($wurl){
        return "url(".quanurl($em[2],$wurl).")";
    }, $nr);
    return $nr;
}

function dirname2($wurl)
{
    if (substr($wurl, -1, 1) == "/") {
        return substr($wurl, 0, -1);
    } else {
        return dirname($wurl);
    }
}

function getCookie($nr){
    preg_match("/setCookie\:\s*([^<>]+)$/",$nr,$nn);
    return $nn[1];
}


function getCookies($nr,$cookie){
    preg_match_all("/Set-Cookie\:\s+(.*)(?:$|(?:path|domain|expires)\s*=)/Uimx",$nr,$nn);
    $cstr="$cookie";
    for($i=0;$i<count($nn[1]);$i++){
        $cstr.=";".trim($nn[1][$i]);
    }

    preg_match_all("/document\.cookie=['\"]([^<>]*)['\"]/Uimx",$nr,$nn);
    for($i=0;$i<count($nn[1]);$i++){
        $cstr.=";".trim($nn[1][$i]);
    }


    $str=preg_replace("/\;+/",";",$cstr);
    $str=preg_replace("/^\;/","",$str);
    $nn=explode(";",$str);
    $arr=array();
    $arr2=array();
    foreach($nn as $k=>$v){
        $ar=explode("=",$v);
        if(trim($ar[0])!=""){
            $arr2[trim($ar[0])]=trim($ar[1]);
        }
    }
    $s="";
    foreach($arr2 as $k=>$v){
        $s.=$k."=".$v.";";
    }
    return $s;
}

function addsla($yy)
{
    $restr = str_replace("\\", "\\\\\\", $yy);
    $restr = str_replace(".*", "allall", $yy);
    $restr = str_replace(".", "\.", $restr);
    $restr = preg_replace("/\\\$/Uisx", "\\\\\\\\\\\\$", $restr);
    $restr = preg_replace("/\"/Uisx", "\\\"", $restr);
    $restr = preg_replace("/\-/Uisx", "\\-", $restr);
    $restr = preg_replace("/\:/Uisx", "\\:", $restr);
    $restr = preg_replace("/\?/Uisx", "\\?", $restr);
    $restr = preg_replace("/\//Uisx", "\\/", $restr);
    $restr = preg_replace("/\{/Uisx", "\\{", $restr);
    $restr = preg_replace("/\}/Uisx", "\\}", $restr);
    $restr = preg_replace("/\(/Uisx", "\\(", $restr);
    $restr = preg_replace("/\)/Uisx", "\\)", $restr);
    $restr = preg_replace("/\|/Uisx", "\\|", $restr);
    $restr = preg_replace("/\,/Uisx", "\\,", $restr);
    $restr = preg_replace("/\!/Uisx", "\\!", $restr);
    $restr = preg_replace("/\^/Uisx", "\\^", $restr);
    //$restr = preg_replace("/\*/Uisx", ".*", $restr);
    $restr = preg_replace("/\#/Uisx", "\\#", $restr);
    $restr = preg_replace("/\]/Uisx", "\\]", $restr);
    $restr = preg_replace("/\[/Uisx", "\\[", $restr);
    $restr = preg_replace("/\+/Uisx", "\\+", $restr);
    $restr = preg_replace("/((\\s\+)?(\\n)?\\s)+/m", "\\\s+", $restr);
    $restr = preg_replace("/MMM$/Uisx", "", $restr);
    $restr = preg_replace("/\\\\s\+MMM\\\\s\+/", "[\s\\n]+", $restr);
    $restr = str_replace("allall", ".*", $restr);
    return $restr;
}

function setVars(){
    session_id(SESS_ID);
    session_start();
    $data=array();
    $data['get']=$_GET;
    $data['post']=$_POST;
    $data['session']=$_SESSION;
    $data['cookie']=$_COOKIE;
    $data['HTTP_RAW_POST_DATA'] = $GLOBALS["HTTP_RAW_POST_DATA"];
    $data['url']="http://{$_SERVER[HTTP_HOST]}{$_SERVER[REQUEST_URI]}";
    $fn=fopen("./vars.txt","w");//保证好执行文件目录下存在vars.txt文件，并权限是7777，请以比较工具查看数据避免缓存，url是请求的具体网址
    fwrite($fn,json_encode($data));
    fclose($fn);
    //echo "<pre>".print_r($data,1)."</pre>";
    //exit;
}

function getVars(){
    session_id(SESS_ID);
    session_start();
    $fn=fopen("./vars.txt","r");
    $json=fread($fn,filesize("./vars.txt"));
    fclose($fn);
    $data=json_decode($json,1);
    $_GET=$data['get'];
    $_POST=$data['post'];
    $GLOBALS["HTTP_RAW_POST_DATA"]=$data['HTTP_RAW_POST_DATA'];
    //$msg = (array)simplexml_load_string($GLOBALS["HTTP_RAW_POST_DATA"] ,'SimpleXMLElement', LIBXML_NOCDATA);
    $_SESSION=$data['session'];
    $_COOKIE=$data['cookie'];
}

function delr($nr){
    $nr=preg_replace("/\r/","",$nr);
    return $nr;
}


function createdir($filepath)
{
    $nn = preg_split("/(?<!\:)\//", $filepath);
    $temppath = "";
    for ($i = 0; $i < count($nn); $i++) {
        $temppath .= (($i > 0) ? "/" : "") . $nn[$i];
        if (!is_dir($temppath)) {
            @mkdir($temppath, 0777);
        }
    }
}


?>